class basePrint {
  name // 插件名称
  url // 连接url
  msg='打印插件尝试连接中...请重试' // 连接信息
  connect // 是否正常链接
  socket
  constructor(name, url) {
    this.name = name
    this.url = url
    this.connect = false
  }
}

basePrint.prototype.init = init

basePrint.prototype.send = send

basePrint.prototype.print = print

basePrint.prototype.getRequestObject = getRequestObject

basePrint.prototype.getUUID = getUUID

async function init(filename) {
  const socket = new WebSocket(this.url)
  const that = this
  await new Promise(function(resovle, reject) {
    // 打开Socket
    socket.onopen = function(event) {
      console.info(that.name + '连接成功')
      that.connect = true
      that.msg = ''
      resovle(socket)
    }
    // 连接错误
    socket.onerror = function() {
      const msg = that.name + '连接发生错误，请确认是否安装并启动插件，或点击这里<a href="javascript:;" class="donwLink" filename="' + filename + '.exe">下载执行安装</a>'
      that.connect = false
      that.msg = msg
      // console.error(msg)
      reject(msg)
    }
    // 连接关闭
    socket.onclose = function(event) {
      const msg = that.name + '连接关闭，请确认是否安装并启动插件，或点击这里<a href="javascript:;" class="donwLink" filename="' + filename + '.exe">下载执行安装</a>'
      that.msg = msg
      that.connect = false
      // console.error(msg)
    }
    // 接受消息
    socket.onmessage = function(event) {
      console.log(that.name + '接受信息：' + event)
    }
  })
  this.socket = socket
  return socket
}

function send(cmd) {
  this.socket.send(JSON.stringify(getRequestObject(cmd)))
}
/** *
 *
 * 获取请求的UUID，指定长度和进制,如
 * getUUID(8, 2)   //"01001010" 8 character (base=2)
 * getUUID(8, 10) // "47473046" 8 character ID (base=10)
 * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
 *
 */
function getUUID(len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  var uuid = []; var i
  radix = radix || chars.length
  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
  } else {
    var r
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16
        uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('')
}

/**
 * 构造request对象
 */
function getRequestObject(cmd) {
  return {
    requestID: getUUID(8, 16),
    version: '1.0',
    cmd
  }
}

/**
 * 打印电子面单
 */
function print() {
  console.warn('方法为实现')
}
export default basePrint
